package com.ihighest.app.infox.adapter;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import com.ihighest.app.infox.R;
import com.ihighest.app.infox.tools.NativeImageLoader;
import com.ihighest.app.infox.tools.NativeImageLoader.NativeImageCallBack;


public class GridviewAdapter extends BaseAdapter {

	private String[] str;
	private LayoutInflater inflater;
	private GridView mGridView;
	private Point mPoint;//������װImageView�Ŀ�͸ߵĶ��� 
	private Handler handler = new Handler();
	ViewHolder mViewHolder;
	private ExecutorService executor = Executors.newFixedThreadPool(10);

	public GridviewAdapter(Context context, String[] str,
			GridView mGridView,int width) {
		this.str = str;
		this.mPoint =  new Point(width, width);
		inflater = LayoutInflater.from(context);
		this.mGridView = mGridView;
	}

	@Override
	public int getCount() {
		return str.length;
	}

	@Override
	public Object getItem(int position) {
		return str[position];
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		if (convertView == null) {
			mViewHolder = new ViewHolder();
			convertView = inflater.inflate(R.layout.infox_id_item, null);
			mViewHolder.mImageView =  (ImageView) convertView.findViewById(R.id.id_item_image);
			
			convertView.setTag(mViewHolder);
			
		} else {
			mViewHolder = (ViewHolder) convertView.getTag();
		}

		
		String path = str[position];
		mViewHolder.mImageView.setTag(path);
		
		Bitmap bitmap = NativeImageLoader.getInstance().loadNativeImage(path,mPoint,
				new NativeImageCallBack() {

					@Override
					public void onImageLoader(Bitmap bitmap, String path) {
						ImageView mImageView = (ImageView) mGridView
								.findViewWithTag(path);
						if (bitmap != null && mImageView != null) {
							mImageView.setImageBitmap(bitmap);
						}
					}
				});

		if (bitmap != null) {
			mViewHolder.mImageView.setImageBitmap(bitmap);
		} else {
			mViewHolder.mImageView
					.setImageResource(R.drawable.ic_launcher);
		}

		return convertView;
	}
    
	private void asyncImageLoad(final ImageView mImageView, final String path) {
		executor.submit(new Runnable() {
			
			@Override
			public void run() {
				final Drawable drawable = Drawable.createFromPath(path);
				handler.post(new Runnable() {
					
					@Override
					public void run() {
						mImageView.setImageDrawable(drawable);
						
					}
				});
				
			}
		});
	}

	public static class ViewHolder {
		public ImageView mImageView;
	}

	

}
